<?php

/**
 * LEAGUEMan
 * 
 * Copyright (C) 2007 Marko Bischof
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

switch ($task) {

    case "quickadd":

        $row = LM::getLMTable("Player");
        $row->player_name_first = trim(mosGetParam($_POST, "player_name_first", ""));
        $row->player_name_last  = trim(mosGetParam($_POST, "player_name_last", ""));
        $row->player_name       = trim(mosGetParam($_POST, "player_name", ""));

        if (!$row->check()) {
            LM::redirect("players", "Check failed!");
        }

        if (!$row->store()) {
            LM::redirect("players", "Could not save!");
        }

        LM::redirect("players");
        break;

    case "new":
    case "edit":
        
        $id = intval(mosGetParam($_REQUEST, 'id', $cid[0]));
        $row = LM::getLMTable("Player");

        if ($task == "edit") {
            $row->load($id);
        }

        $template = LM::getTemplate();

        $template->assign("view", "admin/form_players.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("my", $my);
        $template->assign("row", $row);
        $template->display("admin/view.tpl.php");
        break;

    case 'bulkadd':

        $template = LM::getTemplate();

        $template->assign("view", "admin/form_players_bulkadd.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("my", $my);
        $template->display("admin/view.tpl.php");
        break;

    case 'bulksave':

        $playertext = mosGetParam($_POST, "players", "");
        $lines = explode("\r\n", $playertext);

        $i = 0;
        foreach ($lines AS $line) {

            $player = LM::getLMTable("Player");

            if (strpos($line, ",")) {
                list($firstname, $lastname) = explode(",", $line);

                $player->player_name_first = trim($firstname);
                $player->player_name_last  = trim($lastname);
                $player->player_name       = trim($firstname) . " " . trim($lastname);
            } else {
                $player->player_name_first = '';
                $player->player_name_last  = '';
                $player->player_name       = trim($line);
            }

            if (!$player->store()) {
                $i++;
            }
            
        }

        LM::redirect("players", "Bulksave finished with $i Errors");

        break;

    case 'assign':

        if ($project instanceof LM_Table_Project && $team instanceof LM_Table_Team) {

            $total = count($cid);

            $i = 0;
            foreach ($cid AS $id) {

                $ptable = LM::getLMTable("Playermap");
                $ptable->filterbyProject($project->getID());
                $ptable->filterbyTeam($team->getID());
                $ptable->filterbyPlayer($id);

                if ($ptable->getTotalRows() == 0) {
                    $ptable->playermap_player = $id;
                    $ptable->playermap_project = $project->getID();
                    $ptable->playermap_team = $team->getID();
                    if ($ptable->store()) {
                        $i++;
                    }
                }
            }
        }

        LM::redirect("players", "$i players assigned");
        break;

    case 'save':
        $row = LM::getLMTable("Player");
        $row->save($_POST);

        $image = saveImage($mainframe->getCfg("absolute_path") . "/images/stories/leagueman/players/", "upload", "p{$row->player_id}");

        if ($image) {
            $row->player_image = $image;
        }

        if ($row->store()) {
            $msg = "OK";
        } else {
            $msg = "Could not save Player";
        }

        LM::redirect("players");

        break;

    case 'cancel':
        LM::redirect("players");
        break;

    case "remove":

        $total = count($cid);

        $player = LM::getLMTable("Player");

        $deleted = 0;
        for ($i = 0; $i < $total; $i++) {
            $database->setQuery(
                "SELECT COUNT(playermap_player)
                   FROM #__leagueman_playermap
                  WHERE playermap_player = " . intval($cid[$i]
            ));
            if ($database->loadResult() == 0) {
                if ($player->delete($cid[$i])) {
                    $deleted++;
                }
            }
        }

        LM::redirect("players", $deleted . " Players removed successfully");
        break;

    case 'saveplayers':

        $total = count($cid);

        for ($i = 0; $i < $total; $i++) {

            $player_id      = intval($cid[$i]);
            $player_country = $_POST["player_country"][$i];
            $player_born    = $_POST["player_born"][$i];
            $player_weight  = intval($_POST["player_weight"][$i]);
            $player_height  = intval($_POST["player_height"][$i]);
            $player_state   = intval($_POST["player_state"][$i]);

            $query = "UPDATE #__leagueman_player
                         SET player_country = '$player_country',
                             player_born = '$player_born',
                             player_weight = $player_weight,
                             player_height = $player_height,
                             player_state = $player_state
                       WHERE player_id = $player_id";

            $database->setQuery($query);
            if (!$database->query()) {
                LM::redirect("players", $database->getErrorMsg());
                exit();
            }
        }

        LM::redirect("players");
        break;

    case 'search':
    default:
        $limit      = LM::getSessionValueFromRequest("_{$act}_limit_", 'limit', 10);
        $limitstart = LM::getSessionValueFromRequest("_{$act}_limitstart_", 'limitstart', 0);
        $search     = LM::getSessionValueFromRequest("_{$act}_search_", 'search', '*');

        $where = array();
        if ($search && $search != "*") {
            $where[] = "LOWER(p.player_name) LIKE '%$search%'
                     OR LOWER(p.player_name_first) LIKE '%$search%'
                     OR LOWER(p.player_name_last) LIKE '%$search%'";
        }

        $database->setQuery(
            "SELECT COUNT(p.player_id) FROM #__leagueman_player AS p"
                . (count($where) ? " WHERE " . implode(' AND ', $where) : ""
        ));

        $total = $database->loadResult();
        $pageNav = LM::getPageNav($total, $limitstart, $limit, 1);

        if ($project instanceof LM_Table_Project && $team instanceof LM_Table_Team) {

            $sql = "SELECT p.*, pt.playermap_player
                      FROM #__leagueman_player AS p
                 LEFT JOIN #__leagueman_playermap AS pt ON pt.playermap_player = p.player_id AND pt.playermap_project = {$project->project_id} AND pt.playermap_team = {$team->team_id}"
                 . (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
                " ORDER BY p.player_id DESC
                     LIMIT $pageNav->limitstart, $pageNav->limit";
        } else {

            $sql = "SELECT p.* FROM #__leagueman_player AS p"
                 . (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
                " ORDER BY p.player_id DESC
                     LIMIT $pageNav->limitstart, $pageNav->limit";
        }

        $database->setQuery($sql);
        $rows = $database->loadObjectList();

        $template = LM::getTemplate();

        $template->assign("view", "admin/list_players.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("rows", $rows);
        $template->assign("search", $search);
        $template->assign("pageNav", $pageNav);
        $template->assign("act", "players");
        $template->assign("my", $my);

        $template->display("admin/view.tpl.php");
        break;
}